package com.ydm.myapp001.service;

import android.Manifest;
import android.app.DownloadManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.util.Log;

import com.tbruyelle.rxpermissions.RxPermissions;

import java.io.File;

import rx.functions.Action1;

public class DownloadService extends Service {
    private static final String TAG = "YDMLog_DownloadService";
    /**广播接受者*/
    private BroadcastReceiver receiver;
    /**系统下载管理器*/
    private DownloadManager dm;
    /**系统下载器分配的唯一下载任务id，可以通过这个id查询或者处理下载任务*/
    private long enqueue;
    /**TODO下载地址 需要自己修改,这里随便找了一个*/
    private String downloadUrl="http://www.greenfortune.sh.cn/static/apps/cleaner/cleaner.apk";
    
    public DownloadService() {
        Log.d(TAG, "DownloadService()");
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "onCreate()");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "onStartCommand()");

        //1.创建一个广播接收器
        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                install(context);
                //销毁当前的Service
                stopSelf();
            }
        };

        //2.动态方式注册广播接收器 -- 监听"下载任务完成"的广播
        IntentFilter intentFilter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
        registerReceiver(receiver, intentFilter);

        //下载需要"写SD卡权限", targetSdkVersion>=23 需要动态申请权限
        RxPermissions
                .getInstance(this)
                //申请权限
                .request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(new Action1<Boolean>() {
                    @Override
                    public void call(Boolean granted) {
                        if (granted) { //请求成功
                            startDownload(downloadUrl);
                        }
                        else { //请求失败回收当前服务
                            stopSelf();
                        }
                    }
                });



        return Service.START_STICKY;//如果service进程被kill掉，会自动重启
    }

    @Override
    public void onDestroy() {
        Log.d(TAG, "onDestroy()");
        //服务销毁的时候 反注册广播
        unregisterReceiver(receiver);
        super.onDestroy();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        Log.d(TAG, "onBind()");
        return null;
    }




    /**
     * 开始下载
     */
    private void startDownload(String downUrl) {
        //获取系统下载器
        dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
        //设置下载地址
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(downUrl));
        //设置下载文件的类型
        request.setMimeType("application/vnd.android.package-archive");
        //设置下载文件存放位置--文件夹和文件名称
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "MyAppName.apk");
        //设置下载时或者下载完成时，通知栏是否显示
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        request.setTitle("下载MyApp新版本");
        //执行下载，并返回下载任的唯一id
        enqueue = dm.enqueue(request);
    }

    /**
     * 通过隐式意图调用系统安装程序安装APK
     */
    public static void install(Context context) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        //由于没有在Activity环境下启动Activity,需要设置下面的标签
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "MyAppName.apk");
        Uri apkUri; //安装文件的Uri
        //判断版本是否在7.0以上
        if (Build.VERSION.SDK_INT>=24) { //7.0以上
            //参数1 上下文; 参数2 Provider主机地址 和配置文件中保持一致; 参数3 共享的文件
            apkUri = FileProvider.getUriForFile(context, "com.ydm.myapp001.fileProvider", file);
            //添加下面这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
        else {
            apkUri = Uri.fromFile(file);
        }


        //-setDataAndType-
        intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        context.startActivity(intent);
    }
}
